package com.bw.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.bw.domain.State;
import com.bw.service.StateService;
import com.bw.utils.R;
import com.bw.utils.esypoi.ExportsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author :Beyond🎸🎸
 * @date : 2025-03-11 15:42:27
 * @description Rock and Roll
 **/
@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    StateService stateService;

    @RequestMapping("uploadImages")
    @ResponseBody
    public R uploadImages(MultipartFile file, HttpServletRequest request) throws IOException {
        if(file==null || file.isEmpty()){
            return R.ERROR(500,"选择上传文件");
        }
//        获取指定目录径
       String targetPath = request.getServletContext().getRealPath("/images");
//        创建文件上传的目标文件目录
        File targetFilePath = new File(targetPath);
//        如果不存在则创建
        if(!targetFilePath.exists()){
            targetFilePath.mkdirs();
        }
//        获取原始文件名 如上传的a.jpg
        String originalFilename = file.getOriginalFilename();
//       统一上传的文件命名格式 日期+四位随机数+.文件后缀名
        String filename = DateUtil.today()+"-"+ RandomUtil.randomNumbers(4)+originalFilename.substring(originalFilename.lastIndexOf("."));
//       创建目标文件
        File targetFle = new File(targetPath,filename);
//      上传的文件写入到目标文件
        file.transferTo(targetFle);
//      返回文件名前缀通过文件名获取文件
        return R.OK("/images/"+filename);
    }
@RequestMapping("exportExcel")
    @ResponseBody
    public R exportExcel(HttpServletResponse httpServletResponse){

       List<State> stateList = stateService.list(null);
    ExportsUtil.exports(httpServletResponse,State.class,stateList,"报表展示","报销信息","stateMent_");
        return R.OK();
}
}
